<?php

namespace app\controllers;

use Yii;
use app\models\Base;
use app\models\User;
use app\models\OrderInfo;
use app\models\OrderInfoGood;
use app\tools\Re;
use yii\helpers\Url;

class WxPayController extends BaseController
{

	//微信支付
	public function actionPay() {
		$order_sn = Yii::$app->request->post('order_sn', '');
		$order = OrderInfo::find()->where(['order_sn' => $order_sn])->one();
		if (empty($order)) {
			return Re::data(null, '订单信息读取错误', Re::ERROR);
		}
		$amount = [
			'totle' => $order->money * 100
		];
		$body_name = "商品支付订单";
		//微信统一下单
		$param["appid"] = Yii::$app->params['wx_pay']['app_id'];
		$param["mch_id"] = Yii::$app->params['wx_pay']['mch_id'];
		$param["description"] = '商品支付订单';
		$param["nonce_str"] = md5(time().rand().$order_sn);
		$param["out_trade_no"] = $order_sn;
		$param["amount"] = $amount;
		$param["notify_url"] = Yii::$app->params['domain'] . '/wx-pay/notify-order';
		//$sign = $this->getSign($param);
		//$param["sign"] = $sign;
		//$xml = $this->ToXml($param);
		//var_dump($xml);die;
		$url = "https://api.mch.weixin.qq.com/v3/pay/transactions/app";
		$res = $this->curl($url, json_encode($param));
		$prepay_id = $res->prepay_id;
		return Re::data(['prepay_id' => $prepay_id]);
	}

	//微信支付回调(接口回调)
	public function actionNotifyOrder() {
		$testxml  = file_get_contents("php://input");
    $jsonxml = json_encode(simplexml_load_string($testxml, 'SimpleXMLElement', LIBXML_NOCDATA));
    $result = json_decode($jsonxml, true);//转成数组，
    if($result){
	    //如果成功返回了
	    $out_trade_no = $result['out_trade_no'];
	    if($result['return_code'] == 'SUCCESS' && $result['result_code'] == 'SUCCESS'){
				$order = OrderInfo::find()->where(['order_sn' => $out_trade_no])->one();
				if ($order && !$order->state) {//待支付
					$order->state = 1;
					$order->pay_date = time();
					$order->save();
				}
	    }
    }
		$xml = "<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>";
		echo $xml;
	}

	private function ToXml($param) {
		if(!is_array($param) || count($param) <= 0)
		{
    		throw new WxPayException("数组数据异常！");
    	}

    	$xml = "<xml>";
    	foreach ($param as $key=>$val)
    	{
    		if (is_numeric($val)){
    			$xml.="<".$key.">".$val."</".$key.">";
    		}else{
    			$xml.="<".$key."><![CDATA[".$val."]]></".$key.">";
    		}
        }
        $xml.="</xml>";
        return $xml;
	}

	private function getSign($param) {
		//签名步骤一：按字典序排序参数
		ksort($param);
		$string = $this->ToUrlParams($param);
		//签名步骤二：在string后加入KEY
		$string = $string . "&key=".Yii::$app->params['wx_pay']['key'];
		//签名步骤三：MD5加密
		$string = md5($string);
		//签名步骤四：所有字符转为大写
		$result = strtoupper($string);
		return $result;
	}

	/**
	 * 格式化参数格式化成url参数
	 */
	public function ToUrlParams($param)
	{
		$buff = "";
		foreach ($param as $k => $v)
		{
			if($k != "sign" && $v != "" && !is_array($v)){
				$buff .= $k . "=" . $v . "&";
			}
		}

		$buff = trim($buff, "&");
		return $buff;
	}

	private function curl($url, $data)	{
		$curl = curl_init();
		$method = "POST";
		curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $method);
		curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
		curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
		curl_setopt($curl, CURLOPT_TIMEOUT, 3);
		curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
		curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 2);
		curl_setopt($curl, CURLOPT_HEADER, false);
		curl_setopt($curl, CURLOPT_URL, $url);

		$res = curl_exec($curl);
		curl_close($curl);

		return $res;
	}

	private function getIp() {
		$ip = "";
		$env = Yii::$app->params['env'];
		if ($env == 'dev') {//本地环境
			$ip = file_get_contents('http://pv.sohu.com/cityjson?ie=utf-8');
			preg_match('/{.+}/i', $ip, $m);
			$array = json_decode($m[0]);
			$ip = $array->cip;
		} else {
			if (!empty($_SERVER["HTTP_CLIENT_IP"])) {
					$cip = $_SERVER["HTTP_CLIENT_IP"];
			} else if (!empty($_SERVER["HTTP_X_FORWARDED_FOR"])) {
					$cip = $_SERVER["HTTP_X_FORWARDED_FOR"];
			} else if (!empty($_SERVER["REMOTE_ADDR"])) {
					$cip = $_SERVER["REMOTE_ADDR"];
			} else {
					$cip = '';
			}
			preg_match("/[\d\.]{7,15}/", $cip, $cips);
			$ip = isset($cips[0]) ? $cips[0] : 'unknown';
			unset($cips);
		}
		return $ip;
	}
}
